import { AbsFormUtil } from '@abstract/form';
import { Component, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { ISystemMenu } from '@model/system';
import { TreeService } from '@service/tree.service';
import { SystemService } from '@service/system.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { deepClone, isNotEmpty } from '@utils/lang';
import { ResTypeEnum } from '@app/store/dict';
import { AuthService } from '@service/auth.service';
const ID = 123456789;
const resTypeObj = {
	menu: '菜单',
	resources: '目录',
	botton: '按钮'
};

@Component({
	selector: 'app-system-menu',
	templateUrl: './system-menu.component.html',
	styleUrls: ['./system-menu.component.less']
})
export class SystemMenuComponent extends AbsFormUtil implements OnInit {
	ResTypeEnum = ResTypeEnum;
	ID = ID;
	nzLoading = false;
	data = [];
	editData: ISystemMenu = null;
	constructor(
		private systemService: SystemService,
		private nzMessageService: NzMessageService,
		private fb: FormBuilder,
		private treeService: TreeService,
		private authService: AuthService
	) {
		super();
		this.page.limit = 10000;
		this.authList = this.authService.getAuth();
	}
	ngOnInit() {
		this.buildForm();
		this.onSearch();
	}

	buildForm() {
		this.validateForm = this.fb.group({
			resName: []
		});
	}

	async onSearch() {
		this.nzLoading = true;
		this.editData = null;
		const formValue = this.validateForm.value;
		const result = await this.systemService.getResourceList();
		this.nzLoading = false;
		const treeData = this.treeService.convertListToTree(result.list || [], 0);
		this.data = this.treeService.convertTreeToList(treeData);
		this.data.forEach(itm => itm.resTypeName = resTypeObj[itm.resType])
		if (formValue.resName) {
			this.data.forEach(itm => {
				itm.isSel = itm.resName.includes(formValue.resName) || itm.resUrl && itm.resUrl.includes(formValue.resName) || itm.permission && itm.permission.includes(formValue.resName) || itm.resTypeName.includes(formValue.resName);
				itm.expand = true;
			});
		}
		this.data = [...this.data];
		this.page.total = this.data.length;
	}

	collapse(item, $event: boolean) {
		if (!$event) {
			if (item.children) {
				item.children.forEach(d => {
					const target = this.data.find(a => a.id === d.id)!;
					target.expand = false;
					this.collapse(target, false);
				});
			} else {
				return;
			}
		}
	}

	add(item?: ISystemMenu) {
		if (this.editData) {
			this.nzMessageService.info('一次只能编辑一条数据!');
			return;
		}
		if (item) {
			item.expand = true;
		}
		const node = new ISystemMenu();
		// const uuid = getUuid();
		// node.id = uuid;
		if (!item) {
			node.resType = ResTypeEnum.Resources;
			node.resTypeList = [{label: resTypeObj[ResTypeEnum.Resources], value: ResTypeEnum.Resources}, {label: resTypeObj[ResTypeEnum.Menu], value: ResTypeEnum.Menu}];
		}
		if (item?.resType === ResTypeEnum.Resources) {
			node.resType = ResTypeEnum.Menu;
			// node.resTypeList = [{label: resTypeObj[ResTypeEnum.Resources], value: ResTypeEnum.Resources}];
			node.resTypeList = [{label: resTypeObj[ResTypeEnum.Menu], value: ResTypeEnum.Menu}];

			// node.resTypeList = [{label: resTypeObj[ResTypeEnum.Resources], value: ResTypeEnum.Resources}, {label: resTypeObj[ResTypeEnum.Menu], value: ResTypeEnum.Menu}];
		}
		if (item?.resType === ResTypeEnum.Menu) {
			node.resType = ResTypeEnum.Botton;
			node.resTypeList = [{label: resTypeObj[ResTypeEnum.Botton], value: ResTypeEnum.Botton}];
		}
		if (item) {
			item.expand = true;
			item.children = item.children ? item.children : []
		}
		node.id = ID;
		node.level = item ? item.level + 1 : 0;
		node.children = null;
		node.parent = item ? item : null;
		const idx = item ? this.data.findIndex(itm => itm.id === item.id) : -1;
		this.data.splice(idx + 1, 0, node)
		this.data = [...this.data];
		this.editData = node;
	}
	


	edit(item: ISystemMenu) {
		if (this.editData) {
			this.nzMessageService.info('一次只能编辑一条数据!');
			return;
		}
		this.editData = deepClone(item);
	}
	async del(item: ISystemMenu) {
		await this.systemService.deleteResource(item.id);
		this.nzMessageService.success('删除成功');
		// const idx = this.data.findIndex(it => it.id === item.id);
		// this.data.splice(idx, 1);
		this.delChild(item);
		if (item.parent) {
			const id = item.parent.id;
			if (!this.data.some(it => it.parent && it.parent.id === id)) {
				const parent = this.data.find(it => it.id === id);
				parent.children = null;
			}
		}
		this.data = [...this.data];
	}

	delChild(item) {
		const index = this.data.findIndex(it => it.id === item.id);
		this.data.splice(index, 1);
		if (item.children?.length) {
			item.children.forEach(itm => {
				this.delChild(itm);
			});
		}
	}
	async save(item: ISystemMenu) {
		if (!this.editData.resName) {
			this.nzMessageService.error('权限名称不能为空')
			return;
		}
		// if (!this.editData.resUrl && this.editData.resType === ResTypeEnum.Menu) {
		// 	this.nzMessageService.error('链接不能为空')
		// 	return;
		// }
		if (!this.editData.permission && this.editData.resType === ResTypeEnum.Botton) {
			this.nzMessageService.error('权限标识不能为空')
			return;
		}
		if (isNotEmpty(this.editData.resSort)) {
			this.nzMessageService.error('排序不能为空')
			return;
		}
		const message = this.nzMessageService.loading('保存中...')
		const editData = this.editData;
		const body = {
			parentId: editData.parent ? editData.parent.id : 0,
			resType: editData.resType ? editData.resType : '',
			resName: editData.resName,
			id: editData.id === ID ? '' : editData.id,
			resSort: editData.resSort,
			resUrl: editData.resUrl,
			permission: editData.permission
		};
		// if (this.editData.resType === ResTypeEnum.Botton) {
		// 	body['permission'] = editData.permission;
		// }
		// if (this.editData.resType === ResTypeEnum.Menu) {
		// 	resUrl
		// }
		const result = await this.systemService.saveResource(body);
		this.nzMessageService.remove(message.messageId);
		if (result.msg === '60001') {
			this.nzMessageService.info('该部门名称已存在，请重新填写！');
			return;
		}
		item.id === ID ? this.onSearch() : '';
		if (item.id !== ID) {
			item.resName = editData.resName;
			item.resSort = editData.resSort;
			item.resUrl = editData.resUrl;
			item.permission = editData.permission;
			this.editData = null;
		}
		this.nzMessageService.success('保存成功');
	}
	cancel(item: ISystemMenu) {
		// if (String(item.id).length > 10) {
		if (item.id === ID) {
			const idx = this.data.findIndex(it => it.id === item.id);
			this.data.splice(idx, 1);
			this.data = [...this.data];
		}
		this.editData = null;
	}
	expand() {
		this.data.forEach((itm: ISystemMenu) => itm.expand = true)
	}
	fold() {
		this.data.forEach((itm: ISystemMenu) => itm.expand = false)
	}
	limitDecimals = value => {
		return value && String(value).replace(/^[^\d]+/g, '');
	}
}
